package imse.team0.processors;

import imse.team0.orderws.InvalidRequest;
import imse.team0.orderws.data.InvalidationReasonType;
import imse.team0.orderws.data.OrderType;
import org.apache.camel.Exchange;

import java.util.List;

/**
 * @author Eugen, 4/27/12 7:48 PM
 */
public class OrderItemQtyValidator {

    public void process(Exchange exchange) throws InvalidRequest {
        OrderType order = (OrderType) exchange.getIn().getBody(List.class).get(0);
        int totalQuantity = 0;
        InvalidationReasonType reason = null;
        List<InvalidationReasonType.InvalidOrderItem> invalidItems = null;
        boolean isInvalidOrder = false;
        for (OrderType.OrderItem item : order.getOrderItem()) {
            int qty = item.getQty().intValue();
            if (qty < 0) {
                if (!isInvalidOrder) {
                    reason = new InvalidationReasonType();
                    reason.setReceivedOrder(order);
                    invalidItems = reason.getInvalidOrderItem();
                    isInvalidOrder = true;
                }
                InvalidationReasonType.InvalidOrderItem invalidOrderItem = new InvalidationReasonType.InvalidOrderItem();
                invalidOrderItem.setErrorCode(403);
                invalidOrderItem.setOrderItemID(item.getId());
                invalidOrderItem.setText("The requested quantity of <" + qty + "> is not a valid number");
                invalidItems.add(invalidOrderItem);
            } else {
                totalQuantity += qty;
            }
        }

        if (isInvalidOrder) {
            throw new InvalidRequest("Received order is invalid", reason);
        } else {
            exchange.getIn().setHeader("TotalQuantity", new Integer(totalQuantity));
        }
    }
}
